from manim import *

# 设置Text字号
class MyText(Text):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, font_size=38, **kwargs)


class Adding(Scene):
 
    def construct(self):
        a = 1
        b = 1 
        operator = "+"
        # 确保num1和num2转换为字符串，避免类型错误
        num1_str = str(a)
        num2_str = str(b)

        # 问题描述 1+1=？
        expression = f"{num1_str}{operator}{num2_str}=?"
        text = MyText(expression)
        self.display_and_fade_text(self, text)

        # 被加数a
        text_a = MyText(f"被加数{num1_str}的线段表示为")
        self.display_text(self,text_a)
        line_a = Line(start=ORIGIN, end=a*RIGHT).set_color(ORANGE).next_to(text_a, RIGHT)
        self.display_line(line_a)
        group_a =  self.move_group_up(text_a, line_a)

        # 加数b
        text_b = MyText(f"加数{num2_str}的线段表示为")
        self.display_text(text_b)
        line_b = Line(start=ORIGIN, end=b*RIGHT).set_color(GREEN).next_to(text_b, RIGHT).align_to(line_a, LEFT)
        self.display_line(line_b)
        self.move_group_up(group_a,text_b, line_b)

        # 和a+b
        text_ab = MyText(f"{num1_str}+{num2_str}的线段表示为")
        self.display_text(text_ab)
        # 复制line_a
        line_a1 = line_a.copy()
        self.play(line_a1.animate.next_to(text_ab, RIGHT).align_to(line_a, LEFT))
        self.wait(1)
        line_b1 = line_b.copy()
        self.play(line_b1.animate.next_to(line_a1, RIGHT))
        self.wait(1)
        # line_b1移动到line_a1的结束处
        self.play(line_b1.animate.shift(line_a1.get_end()-line_b1.get_start()))
        self.wait(1)
        # line_a1和line_b1淡出
        self.play(FadeOut(line_a1), FadeOut(line_b1))
        self.wait(1)

        # 把line_a1和line_b1合并为一条线段
        line_ab = Line(start=ORIGIN, end=(a+b)*RIGHT).set_color(BLUE)
        line_ab.next_to(text_ab, RIGHT).align_to(line_a, LEFT)
        self.play(Create(line_ab))
        self.wait(1)

        # 绘制Brace
        brace = Brace(line_ab)
        self.play(Create(brace))
        b1text = brace.get_text(f"{a}+{b}={a+b}")
        self.play(Write(b1text))
        self.wait(1)

    def display_line(self, line_a):
        self.play(Create(line_a))
        self.wait(1)

    def move_group_up(self, *mobjects):
        group_a = VGroup(*mobjects)
        self.play(group_a.animate.shift(UP))
        self.wait(1)
        return group_a
    def display_and_fade_text(self, text):
        self.play(Write(text))
        self.wait(1)
        self.play(FadeOut(text))
        self.wait(1)   
    def display_text(self, text):
        self.play(Write(text))
        self.wait(1)






    